<script setup lang="ts">
import { ref, onMounted, defineProps, withDefaults } from "vue";
import { formRules, setOriginalFormName } from "../utils/rule";
import { FormProps } from "../utils/types";
import { usePublicHooks } from "../../hooks";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { message } from "@/utils/message";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import { ElMessage, ElTooltip } from "element-plus";
import { getConfig } from "@/config";

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    name: "",
    subLimit: 20,
    tenantLimit: 20,
    isSealed: 0,
    logo: "",
    address: "",
    contact: "",
    tel: "",
    comment: "",
    loginPwd: "", // 新增初始登录密码字段
    code: ""
  }),
  title: "", // 添加title属性的默认值
  originalName: ""
});
const imageUrl = ref("");
const originalName = ref(props.originalName);
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  // 将上传成功返回的FileKey赋值给logo字段
  newFormInline.value.logo = response.Data.FileKey;
  console.log("FileKey:", newFormInline.value.logo);
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("Logo图片必须是JPG或PNG格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Logo图片大小不能超过2MB!");
    return false;
  }
  return true;
};
const ruleFormRef = ref();
const { switchStyle } = usePublicHooks();
const newFormInline = ref(props.formInline);
const listDealers = ref([]); //下拉列表数据

//获取经销商下拉列表
const getSelectDealers = () => {
  http
    .get(changeHttpLink("/api/Dealer/select"))
    .then((res: any) => {
      if (res.Success) {
        listDealers.value = res.Data;
      } else {
        message(res.Message, { type: "error" });
      }
    })
    .catch(err => {
      message(err.message, { type: "error" });
    });
};

function getRef() {
  return ruleFormRef.value;
}

onMounted(() => {
  getSelectDealers();
  // 设置原始名称
  setOriginalFormName(props.originalName || "");
  console.log(props.formInline);
  // 如果是编辑模式且有logo数据，设置imageUrl
  if (props.formInline.logo) {
    const config = getConfig();
    const baseUrl = config.ApiLinkUrl
      ? config.ApiLinkUrl.replace("/server/", "")
      : "http://192.168.0.105";
    imageUrl.value = baseUrl + props.formInline.logo;
  }
});

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="120px"
    class="w-full"
  >
    <el-form-item label="经销商名称" prop="name" required>
      <el-input v-model="newFormInline.name" placeholder="请输入经销商名称" />
    </el-form-item>
    <el-form-item v-if="title !== '创建'" label="账号" prop="tel" required>
      <el-input
        v-model="newFormInline.tel"
        placeholder="请输入电话号码作为账号"
        :disabled="title !== '创建'"
      />
    </el-form-item>
    <el-row v-if="title === '创建'" :gutter="20">
      <el-col :span="12">
        <el-form-item label="账号" prop="tel" required>
          <el-input
            v-model="newFormInline.tel"
            placeholder="请输入电话号码作为账号"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <!-- 添加初始登录密码 -->
        <el-form-item label="登录密码" prop="loginPwd" required>
          <el-input
            v-model="newFormInline.loginPwd"
            type="password"
            placeholder="请输入初始登录密码"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="联系人" prop="contact">
      <el-input v-model="newFormInline.contact" placeholder="请输入联系人" />
    </el-form-item>
    <el-form-item label="地址" prop="address">
      <el-input
        v-model="newFormInline.address"
        placeholder="请输入地址"
        type="textarea"
      />
    </el-form-item>
    <el-form-item label="Logo">
      <el-upload
        class="avatar-uploader"
        method="post"
        action="/api/File/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item label="是否封闭" prop="isSealed">
      <el-radio-group v-model="newFormInline.isSealed">
        <el-radio :value="1" label="正常" />
        <el-radio :value="0" label="封闭" />
      </el-radio-group>
    </el-form-item>
    <!-- 添加相关备注 -->
    <el-form-item label="备注" prop="comment">
      <el-input
        v-model="newFormInline.comment"
        type="textarea"
        :maxlength="200"
        show-word-limit
        :rows="4"
        placeholder="请输入备注，最多200字"
      />
    </el-form-item>
  </el-form>
</template>
<style scoped>
.avatar-uploader .avatar {
  display: block;
  width: 120px;
  height: 120px;
}
</style>

<style>
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  width: 120px;
  height: 120px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
